#include "models.h"

// User 实现
QJsonObject User::toJson() const {
    QJsonObject json;
    json["id"] = id;
    json["username"] = username;
    json["real_name"] = realName;
    json["id_card"] = idCard;
    json["phone"] = phone;
    json["role"] = role;
    json["create_time"] = createTime.toString(Qt::ISODate);
    return json;
}

User User::fromJson(const QJsonObject& json) {
    User user;
    user.id = json["id"].toInt();
    user.username = json["username"].toString();
    user.password = json["password"].toString();
    user.realName = json["real_name"].toString(); // 使用下划线命名
    user.idCard = json["id_card"].toString();     // 使用下划线命名
    user.phone = json["phone"].toString();
    user.role = json["role"].toInt();
    user.createTime = QDateTime::fromString(json["create_time"].toString(), Qt::ISODate);
    return user;
}

// Patient 实现
QJsonObject Patient::toJson() const {
    QJsonObject json = User::toJson();
    json["gender"] = gender;
    json["birth_date"] = birthDate.toString("yyyy-MM-dd");
    json["address"] = address;
    json["emergency_contact"] = emergencyContact;
    json["emergency_phone"] = emergencyPhone;
    json["allergies"] = allergies;
    json["medical_history"] = medicalHistory;
    return json;
}

Patient Patient::fromJson(const QJsonObject& json) {
    Patient patient;
    User user = User::fromJson(json);
    patient.id = user.id;
    patient.username = user.username;
    patient.password = user.password;
    patient.realName = user.realName;
    patient.idCard = user.idCard;
    patient.phone = user.phone;
    patient.role = user.role;
    patient.createTime = user.createTime;
    
    // 支持下划线命名
    patient.gender = json["gender"].toString();
    patient.birthDate = QDate::fromString(json["birth_date"].toString(), "yyyy-MM-dd");
    patient.address = json["address"].toString();
    patient.emergencyContact = json["emergency_contact"].toString();
    patient.emergencyPhone = json["emergency_phone"].toString();
    patient.allergies = json["allergies"].toString();
    patient.medicalHistory = json["medical_history"].toString();
    
    // 如果有 user_id 字段，优先使用（用于更新请求）
    if (json.contains("user_id")) {
        patient.id = json["user_id"].toInt();
    }
    
    return patient;
}

// Doctor 实现
QJsonObject Doctor::toJson() const {
    QJsonObject json = User::toJson();
    json["department_id"] = departmentId;
    json["department_name"] = departmentName;
    json["title"] = title;
    json["specialty"] = specialty;
    json["education"] = education;
    json["experience"] = experience;
    json["introduction"] = introduction;
    json["work_time"] = workTime;
    json["consultation_fee"] = consultationFee;
    json["daily_patient_limit"] = dailyPatientLimit;
    json["booked_count"] = bookedCount;
    json["remaining_slots"] = remainingSlots;
    json["clinic_type"] = clinicType;
    return json;
}

Doctor Doctor::fromJson(const QJsonObject& json) {
    Doctor doctor;
    User user = User::fromJson(json);
    doctor.id = user.id;
    doctor.username = user.username;
    doctor.password = user.password;
    doctor.realName = user.realName;
    doctor.idCard = user.idCard;
    doctor.phone = user.phone;
    doctor.role = user.role;
    doctor.createTime = user.createTime;
    
    // 支持下划线命名
    doctor.departmentId = json["department_id"].toInt();
    doctor.departmentName = json["department_name"].toString();
    doctor.title = json["title"].toString();
    doctor.specialty = json["specialty"].toString();
    doctor.education = json["education"].toString();
    doctor.experience = json["experience"].toInt();
    doctor.introduction = json["introduction"].toString();
    doctor.workTime = json["work_time"].toString();
    doctor.consultationFee = json["consultation_fee"].toDouble();
    doctor.dailyPatientLimit = json["daily_patient_limit"].toInt();
    doctor.bookedCount = json["booked_count"].toInt();
    doctor.remainingSlots = json["remaining_slots"].toInt();
    doctor.clinicType = json["clinic_type"].toString();
    
    // 如果有 user_id 字段，优先使用（用于更新请求）
    if (json.contains("user_id")) {
        doctor.id = json["user_id"].toInt();
    }
    
    return doctor;
}

// Appointment 实现
QJsonObject Appointment::toJson() const {
    QJsonObject json;
    json["id"] = id;
    json["patient_id"] = patientId;
    json["doctor_id"] = doctorId;
    json["appointment_time"] = appointmentTime.toString("yyyy-MM-dd HH:mm:ss");
    json["status"] = status;
    json["cancel_reason"] = cancelReason;
    json["symptoms"] = symptoms;
    json["medical_record_id"] = medicalRecordId;
    json["create_time"] = createTime.toString(Qt::ISODate);
    return json;
}

Appointment Appointment::fromJson(const QJsonObject& json) {
    Appointment appointment;
    appointment.id = json["id"].toInt();
    appointment.patientId = json["patient_id"].toInt();
    appointment.doctorId = json["doctor_id"].toInt();
    appointment.appointmentTime = QDateTime::fromString(json["appointment_time"].toString(), "yyyy-MM-dd HH:mm:ss");
    appointment.status = json["status"].toString();
    appointment.cancelReason = json["cancel_reason"].toString();
    appointment.symptoms = json["symptoms"].toString();
    appointment.medicalRecordId = json["medical_record_id"].toInt();
    appointment.createTime = QDateTime::fromString(json["create_time"].toString(), Qt::ISODate);
    return appointment;
}

// MedicalRecord 实现
QJsonObject MedicalRecord::toJson() const {
    QJsonObject json;
    json["id"] = id;
    json["patient_id"] = patientId;
    json["doctor_id"] = doctorId;
    json["appointment_id"] = appointmentId;
    json["doctor_name"] = doctorName;
    json["visit_time"] = visitTime.toString("yyyy-MM-dd HH:mm:ss");
    json["chief_complaint"] = chiefComplaint;
    json["present_illness"] = presentIllness;
    json["physical_exam"] = physicalExam;
    json["diagnosis"] = diagnosis;
    json["treatment"] = treatment;
    json["notes"] = notes;
    return json;
}

MedicalRecord MedicalRecord::fromJson(const QJsonObject& json) {
    MedicalRecord record;
    record.id = json["id"].toInt();
    record.patientId = json["patient_id"].toInt();
    record.doctorId = json["doctor_id"].toInt();
    record.appointmentId = json["appointment_id"].toInt();
    record.doctorName = json["doctor_name"].toString();
    record.visitTime = QDateTime::fromString(json["visit_time"].toString(), "yyyy-MM-dd HH:mm:ss");
    record.chiefComplaint = json["chief_complaint"].toString();
    record.presentIllness = json["present_illness"].toString();
    record.physicalExam = json["physical_exam"].toString();
    record.diagnosis = json["diagnosis"].toString();
    record.treatment = json["treatment"].toString();
    record.notes = json["notes"].toString();
    return record;
}

// Prescription 实现
QJsonObject Prescription::toJson() const {
    QJsonObject json;
    json["id"] = id;
    json["medical_record_id"] = medicalRecordId;
    json["patient_id"] = patientId;
    json["doctor_id"] = doctorId;
    json["appointment_id"] = appointmentId;
    json["prescription_time"] = prescriptionTime.toString("yyyy-MM-dd HH:mm:ss");
    json["medications"] = medications;
    json["dosage"] = dosage;
    json["usage"] = usage;
    json["frequency"] = frequency;
    json["days"] = days;
    json["notes"] = notes;
    return json;
}

Prescription Prescription::fromJson(const QJsonObject& json) {
    Prescription prescription;
    prescription.id = json["id"].toInt();
    prescription.medicalRecordId = json["medical_record_id"].toInt();
    prescription.patientId = json["patient_id"].toInt();
    prescription.doctorId = json["doctor_id"].toInt();
    prescription.appointmentId = json["appointment_id"].toInt();
    prescription.prescriptionTime = QDateTime::fromString(json["prescription_time"].toString(), "yyyy-MM-dd HH:mm:ss");
    prescription.medications = json["medications"].toString();
    prescription.dosage = json["dosage"].toString();
    prescription.usage = json["usage"].toString();
    prescription.frequency = json["frequency"].toString();
    prescription.days = json["days"].toInt();
    prescription.notes = json["notes"].toString();
    return prescription;
}

// ExamRequest 实现
QJsonObject ExamRequest::toJson() const {
    QJsonObject json;
    json["id"] = id;
    json["medical_record_id"] = medicalRecordId;
    json["patient_id"] = patientId;
    json["doctor_id"] = doctorId;
    json["exam_type"] = examType;
    json["exam_item"] = examItem;
    json["purpose"] = purpose;
    json["status"] = status;
    json["result"] = result;
    json["request_time"] = requestTime.toString("yyyy-MM-dd HH:mm:ss");
    json["result_time"] = resultTime.toString("yyyy-MM-dd HH:mm:ss");
    return json;
}

ExamRequest ExamRequest::fromJson(const QJsonObject& json) {
    ExamRequest exam;
    exam.id = json["id"].toInt();
    exam.medicalRecordId = json["medical_record_id"].toInt();
    exam.patientId = json["patient_id"].toInt();
    exam.doctorId = json["doctor_id"].toInt();
    exam.examType = json["exam_type"].toString();
    exam.examItem = json["exam_item"].toString();
    exam.purpose = json["purpose"].toString();
    exam.status = json["status"].toString();
    exam.result = json["result"].toString();
    exam.requestTime = QDateTime::fromString(json["request_time"].toString(), "yyyy-MM-dd HH:mm:ss");
    exam.resultTime = QDateTime::fromString(json["result_time"].toString(), "yyyy-MM-dd HH:mm:ss");
    return exam;
}

// Department 实现
QJsonObject Department::toJson() const {
    QJsonObject json;
    json["id"] = id;
    json["name"] = name;
    json["description"] = description;
    json["location"] = location;
    json["phone"] = phone;
    return json;
}

Department Department::fromJson(const QJsonObject& json) {
    Department dept;
    dept.id = json["id"].toInt();
    dept.name = json["name"].toString();
    dept.description = json["description"].toString();
    dept.location = json["location"].toString();
    dept.phone = json["phone"].toString();
    return dept;
}

// Payment 实现
QJsonObject Payment::toJson() const {
    QJsonObject json;
    json["id"] = id;
    json["patient_id"] = patientId;
    json["payment_type"] = paymentType;
    json["amount"] = amount;
    json["status"] = status;
    json["description"] = description;
    json["payment_time"] = paymentTime.toString("yyyy-MM-dd HH:mm:ss");
    return json;
}

Payment Payment::fromJson(const QJsonObject& json) {
    Payment payment;
    payment.id = json["id"].toInt();
    payment.patientId = json["patient_id"].toInt();
    payment.paymentType = json["payment_type"].toString();
    payment.amount = json["amount"].toDouble();
    payment.status = json["status"].toString();
    payment.description = json["description"].toString();
    payment.paymentTime = QDateTime::fromString(json["payment_time"].toString(), "yyyy-MM-dd HH:mm:ss");
    return payment;
}

// Message 实现
QJsonObject Message::toJson() const {
    QJsonObject json;
    json["id"] = id;
    json["sender_id"] = senderId;
    json["receiver_id"] = receiverId;
    json["message_content"] = messageContent;
    json["send_time"] = sendTime.toString("yyyy-MM-dd HH:mm:ss");
    json["is_read"] = isRead;
    json["sender_name"] = senderName;
    json["receiver_name"] = receiverName;
    return json;
}

Message Message::fromJson(const QJsonObject& json) {
    Message msg;
    msg.id = json["id"].toInt();
    msg.senderId = json["sender_id"].toInt();
    msg.receiverId = json["receiver_id"].toInt();
    msg.messageContent = json["message_content"].toString();
    msg.sendTime = QDateTime::fromString(json["send_time"].toString(), "yyyy-MM-dd HH:mm:ss");
    msg.isRead = json["is_read"].toBool();
    msg.senderName = json["sender_name"].toString();
    msg.receiverName = json["receiver_name"].toString();
    return msg;
}

// AttendanceRecord 实现
QJsonObject AttendanceRecord::toJson() const {
    QJsonObject json;
    json["id"] = id;
    json["doctor_id"] = doctorId;
    json["attendance_date"] = attendanceDate.toString("yyyy-MM-dd");
    json["attendance_time"] = attendanceTime.toString("HH:mm:ss");
    json["create_time"] = createTime.toString("yyyy-MM-dd HH:mm:ss");
    return json;
}

AttendanceRecord AttendanceRecord::fromJson(const QJsonObject& json) {
    AttendanceRecord record;
    record.id = json["id"].toInt();
    record.doctorId = json["doctor_id"].toInt();
    record.attendanceDate = QDate::fromString(json["attendance_date"].toString(), "yyyy-MM-dd");
    record.attendanceTime = QTime::fromString(json["attendance_time"].toString(), "HH:mm:ss");
    record.createTime = QDateTime::fromString(json["create_time"].toString(), "yyyy-MM-dd HH:mm:ss");
    return record;
}

// LeaveRequest 实现
QJsonObject LeaveRequest::toJson() const {
    QJsonObject json;
    json["id"] = id;
    json["doctor_id"] = doctorId;
    json["phone"] = phone;
    json["leave_type"] = leaveType;
    json["start_date"] = startDate.toString("yyyy-MM-dd");
    json["end_date"] = endDate.toString("yyyy-MM-dd");
    json["reason"] = reason;
    json["status"] = status;
    json["request_time"] = requestTime.toString("yyyy-MM-dd HH:mm:ss");
    if (cancelTime.isValid()) {
        json["cancel_time"] = cancelTime.toString("yyyy-MM-dd HH:mm:ss");
    }
    return json;
}

LeaveRequest LeaveRequest::fromJson(const QJsonObject& json) {
    LeaveRequest request;
    request.id = json["id"].toInt();
    request.doctorId = json["doctor_id"].toInt();
    request.phone = json["phone"].toString();
    request.leaveType = json["leave_type"].toString();
    request.startDate = QDate::fromString(json["start_date"].toString(), "yyyy-MM-dd");
    request.endDate = QDate::fromString(json["end_date"].toString(), "yyyy-MM-dd");
    request.reason = json["reason"].toString();
    request.status = json["status"].toString();
    request.requestTime = QDateTime::fromString(json["request_time"].toString(), "yyyy-MM-dd HH:mm:ss");
    if (json.contains("cancel_time") && !json["cancel_time"].isNull()) {
        request.cancelTime = QDateTime::fromString(json["cancel_time"].toString(), "yyyy-MM-dd HH:mm:ss");
    }
    return request;
}

// Medicine 实现
QJsonObject Medicine::toJson() const {
    QJsonObject json;
    json["id"] = id;
    json["name"] = name;
    json["category"] = category;
    json["manufacturer"] = manufacturer;
    json["specification"] = specification;
    json["price"] = price;
    json["usage_instruction"] = usageInstruction;
    json["precautions"] = precautions;
    json["is_popular"] = isPopular;
    json["create_time"] = createTime.toString("yyyy-MM-dd HH:mm:ss");
    return json;
}

Medicine Medicine::fromJson(const QJsonObject& json) {
    Medicine medicine;
    medicine.id = json["id"].toInt();
    medicine.name = json["name"].toString();
    medicine.category = json["category"].toString();
    medicine.manufacturer = json["manufacturer"].toString();
    medicine.specification = json["specification"].toString();
    medicine.price = json["price"].toDouble();
    medicine.usageInstruction = json["usage_instruction"].toString();
    medicine.precautions = json["precautions"].toString();
    medicine.isPopular = json["is_popular"].toBool();
    medicine.createTime = QDateTime::fromString(json["create_time"].toString(), "yyyy-MM-dd HH:mm:ss");
    return medicine;
}

// Notification 实现
QJsonObject Notification::toJson() const {
    QJsonObject json;
    json["id"] = id;
    json["user_id"] = userId;
    json["user_role"] = userRole;
    json["type"] = type;
    json["title"] = title;
    json["content"] = content;
    json["related_id"] = relatedId;
    json["is_read"] = isRead;
    json["create_time"] = createTime.toString("yyyy-MM-dd HH:mm:ss");
    return json;
}

Notification Notification::fromJson(const QJsonObject& json) {
    Notification notification;
    notification.id = json["id"].toInt();
    notification.userId = json["user_id"].toInt();
    notification.userRole = json["user_role"].toInt();
    notification.type = json["type"].toString();
    notification.title = json["title"].toString();
    notification.content = json["content"].toString();
    notification.relatedId = json["related_id"].toInt();
    notification.isRead = json["is_read"].toBool();
    notification.createTime = QDateTime::fromString(json["create_time"].toString(), "yyyy-MM-dd HH:mm:ss");
    return notification;
}

